package cn.edu.hbpu.common.interceptor;

import cn.edu.hbpu.pojo.StudentCustom;
import cn.edu.hbpu.pojo.Teacher;
import cn.edu.hbpu.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @Author yuwenteng
 * @Date 2017/10/14 15:04
 * @Description 处理rememberMe自动登录后session失效的过滤器
 */
public class RememberMeFilter extends AccessControlFilter {

    @Autowired
    private LoginService loginService;

    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o) throws Exception {
        //获取当前的subject对象
        Subject subject = SecurityUtils.getSubject();
        //判断用户是不是通过记住我功能自动登录,此时session失效
        if (!subject.isAuthenticated() && subject.isRemembered()) {
            //根据自动登录信息查询数据库中用户信息
            StudentCustom studentCustom = loginService.getStudentInfoByName((String) subject.getPrincipal());
            if (studentCustom != null) {
                //对自动登录密码进行验证
                UsernamePasswordToken token = new UsernamePasswordToken(studentCustom.getStuName(), studentCustom.getPassword(), subject.isRemembered());
                try {
                    subject.login(token);
                    return true;
                } catch (AuthenticationException ae) {
                    //自动登录出现异常跳转登录页面
                    request.getRequestDispatcher("/login/showLoginPage").forward(request, response);
                    return false;
                }
            } else {
                //根据自动登录信息查询数据库中用户信息
                Teacher teacher = loginService.getTeacherInfoByName((String) subject.getPrincipal());
                //对自动登录密码进行验证
                UsernamePasswordToken token = new UsernamePasswordToken(teacher.getTeacherName(), teacher.getTeacherPassword(), subject.isRemembered());
                try {
                    subject.login(token);
                    return true;
                } catch (AuthenticationException ae) {
                    //自动登录出现异常跳转登录页面
                    request.getRequestDispatcher("/login/showLoginPage").forward(request, response);
                    return false;
                }
            }
        } else if (!subject.isAuthenticated()) {
            //判断当前用户是否已经被认证，即是否已经登录,如果不是，则跳转登录页面
            request.getRequestDispatcher("/login/showLoginPage").forward(request, response);
            return false;
        } else {
            //如果当前用户是已经被认证，即是否已经登录，则放过
            return true;
        }
    }

    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return false;
    }
}
